import React, { useEffect, useState, useRef, Suspense } from 'react'
import { Layout, Menu,  Button, Row, Col, Spin, Modal, message,Input} from 'antd';
import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'
import CheckLogingState from '../../js/CheckLoginState'

import {
    MenuUnfoldOutlined,
    MenuFoldOutlined,
    EditOutlined,
    HeartOutlined,
    GiftOutlined,
    LogoutOutlined,
    PieChartOutlined,
    RedoOutlined
} from '@ant-design/icons';
import {
    DataPage,
    AllUser, AllOrg, AllOrgApply,
    AllType, AllChange, AllDonation, AllChangeHistory,
    AllGift, AllGiftHistory,
    AllGoods

} from '../../js/AllPage'
import axios from 'axios';
const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;
export default function Index() {

    const [collapsed, setCollapsed] = useState(false);
    const [loginUser, setLoginUser] = useState(JSON.parse(localStorage.getItem("loginUser")))
    const navigate = useNavigate();
    const [logoutVisible, setlogoutVisible] = useState(false)
    const newPwd = useRef()
    const checkPwd = useRef()
    useEffect(async () => {
        message.destroy();
        if (loginUser.role === 1) navigate('/userMenu/*')
        let checkLoginUserRs = await CheckLogingState(loginUser)
        if (checkLoginUserRs.state === "0") {
            localStorage.setItem("loginUser", checkLoginUserRs.loginUser)
            setLoginUser(JSON.parse(localStorage.getItem("loginUser")));
            if (loginUser.role === 1) navigate('/userMenu/*')
        }
        if (checkLoginUserRs.state === "3") {
            localStorage.clear();
            message.error(checkLoginUserRs.message)
            navigate("/LoginAndRegister/*")
        }
    }, [])
    const togglecollapsed = () => {
        let t = collapsed;
        setCollapsed(!t)
    }
    const logout = () => {
        console.log('LOGOUT');
        localStorage.clear();
        navigate("/*");
    }
    const pwdChange = () => {
        const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
        message.destroy()
        Modal.confirm({
            title: '修改密码',
            content:<>
                 <Input placeholder="新密码" type="password" ref={newPwd}/> 
                 <br /><br /> 
                 <Input placeholder="再次输入" type="password" ref={checkPwd}/>
            </>,
            async onOk() {
               if (newPwd.current.state.value !=checkPwd.current.state.value) {
                   message.error("两次密码不一致!")
                   return
               }
              if(pwdReg.test(newPwd.current.state.value)){
                  let params = {id:loginUser.id,password:newPwd.current.state.value}
                const resp = await axios.post("http://localhost:8080/editUser",params)
                if (resp.data.state=="0") {
                    message.success(resp.data.message)
                    navigate('/')
                    window.location.reload();
                }
              }else{
                  message.error("密码为6-18位数字字母组合!")
                  return 
              }
            },
        });
    }
    return (
        <Layout style={{ height: '100%', minHeight: '100VH' }}>
            <Sider trigger={null} collapsible collapsed={collapsed}>
                <Menu
                    mode="inline"
                    defaultSelectedKeys={['111']}
                    defaultOpenKeys={['sub1']}
                    style={{ height: '100%' }}
                    theme="dark"
                >
                    <Menu.Item key="111" style={{ fontWeight: '400' }} icon={<PieChartOutlined />} onClick={() => { navigate('dataPage/*') }}>系统数据</Menu.Item>
                    <SubMenu key="sub1" style={{ fontWeight: '700' }} title="成员管理" icon={<EditOutlined />}>
                        <Menu.Item key="11" style={{ fontWeight: '400' }} onClick={() => { navigate('allUser/*') }}>普通用户</Menu.Item>
                        <Menu.Item key="12" style={{ fontWeight: '400' }} onClick={() => { navigate('allOrg/*') }}>爱心机构</Menu.Item>
                        <Menu.Item key="13" style={{ fontWeight: '400' }} onClick={() => { navigate('allOrgApply/*') }}>机构审批</Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub4" style={{ fontWeight: '700' }} title="旧物交换" icon={<RedoOutlined />}>

                        <Menu.Item key="41" style={{ fontWeight: '400' }} onClick={() => { navigate(`allType/*`) }}>类别管理</Menu.Item>
                        <Menu.Item key="42" style={{ fontWeight: '400' }} onClick={() => { navigate('allChange/*') }}>当前交换物品</Menu.Item>
                        <Menu.Item key="43" style={{ fontWeight: '400' }} onClick={() => { navigate('allChangeHistory/*') }}>历史交换</Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub2" style={{ fontWeight: '700' }} title="旧物捐赠" icon={<HeartOutlined />}>
                        <Menu.Item key="21" style={{ fontWeight: '400' }} onClick={() => { navigate('allGoods/*') }}>类别管理</Menu.Item>
                        <Menu.Item key="22" style={{ fontWeight: '400' }} onClick={() => { navigate('allDonation/*') }}>历史捐赠</Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub3" style={{ fontWeight: '700' }} title="兑换管理" icon={<GiftOutlined />}>
                        <Menu.Item key="31" style={{ fontWeight: '400' }} onClick={() => { navigate(`allGift/*`) }}>礼物管理</Menu.Item>
                        <Menu.Item key="32" style={{ fontWeight: '400' }} onClick={() => { navigate(`allGiftHistory/*`) }}>兑换管理</Menu.Item>
                    </SubMenu>
                </Menu>
            </Sider>
            <Layout>
                <Header style={{ backgroundColor: "#FFF", display: 'flex', justifyContent: 'space-between', alignItems: 'center', }}>
                    <Row align="middle">
                        <Col>
                            {
                                collapsed == true ? <a onClick={togglecollapsed}><MenuUnfoldOutlined style={{ fontSize: 20 }} /></a> : <a onClick={togglecollapsed}><MenuFoldOutlined style={{ fontSize: 20 }} /></a>
                            }
                        </Col>
                    </Row>
                    <Row >
                        <Col span={8} ><Button type="primary" onClick={pwdChange}>修改密码</Button></Col>
                        <Col span={8} offset={8}><Button danger type="primary" onClick={() => { setlogoutVisible(true) }}><LogoutOutlined />退出</Button></Col>
                    </Row>

                </Header>
                <Content
                    className="pageBg"
                    style={{
                        margin: `0.5%`,
                        padding: `1%`,
                        minHeight: `100%VH`,
                        backgroundColor: '#fff',
                        height: '100%'
                    }}
                >
                    <Suspense fallback={<Spin size='large' />}>
                        <Routes>
                            <Route path='/dataPage/*' element={<DataPage />} />
                            <Route path='/allOrg/*' element={<AllOrg />} />
                            <Route path='/allOrgApply/*' element={<AllOrgApply />} />
                            <Route path='/allUser/*' element={<AllUser />} />
                            <Route path='/allType/*' element={<AllType />} />
                            <Route path='/allDonation/*' element={<AllDonation />} />
                            <Route path='/allChange/*' element={<AllChange />} />
                            <Route path='/allChangeHistory/*' element={<AllChangeHistory />} />
                            <Route path='/allGoods/*' element={<AllGoods />} />
                            <Route path='/allGift/*' element={<AllGift />} />
                            <Route path='/allGiftHistory/*' element={<AllGiftHistory />} />
                            <Route path={'*'} element={<Navigate to='dataPage' />} />
                        </Routes>
                    </Suspense>
                </Content>
            </Layout>
            <Modal title="提示" visible={logoutVisible} onOk={logout} onCancel={() => { setlogoutVisible(false) }}>
                <p>确认要退出吗?</p>
            </Modal>
        </Layout >
    )
}
